package com.huarun.module.sms.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.huarun.common.BaseController;
import com.huarun.common.ResponseMessage;
import com.huarun.common.util.Constant;
import com.huarun.common.util.ResultCodeEnum;
import com.huarun.common.util.ResultCodeValue;
import com.huarun.common.util.SMSConstant;
import com.huarun.common.util.SMSUtil;
import com.huarun.common.util.SpringUtils;
import com.huarun.common.util.VerityUtil;
import com.huarun.module.sms.bean.SmsMobile;
import com.huarun.module.sms.service.ISmsMobileService;
import com.huarun.module.user.bean.User;
import com.huarun.module.user.service.IUserService;
import com.huarun.module.user.util.LesseeInfoUtil;
import com.huarun.redis.RedisKeyPrefix;
import com.huarun.redis.RedisUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author zy
 * @创建时间 2018-08-07 10:33
 * @Description 类描述
 */
@Api(description = "短信")
@RequestMapping("/SMS")
@Controller
public class SMSSendController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(SMSSendController.class);

	@Resource
	private IUserService userService;
	@Resource
	private ISmsMobileService smsMobileService;
	
	@ApiOperation(notes = "腾讯单发短信入口", value = "腾讯单发短信入口")
	@RequestMapping(value = "/tdSmsSingleSend", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage<Object> SmsSingleSend(@RequestBody Map<String, Object> param) {
		ResponseMessage<Object> rm = new ResponseMessage<Object>();
		try {
			String mobile = String.valueOf(param.get("mobile"));
			if (!VerityUtil.isMobile(mobile)) {
				rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "请输入正确的手机号码");
				return rm;
			}
			String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
			String minute = Constant.TENCENT_SMS_FORGET_PASSWORD_MINUTE;
			String content = Constant.TENCENT_SMS_FORGET_PASSWORD_CONTENT.replace("verifyCode", verifyCode)
					.replace("minute", minute);
			rm = SMSUtil.sendSMS(mobile, content);
			SmsMobile entity=new SmsMobile();
			entity.setMobile(mobile);
			entity.setVerifycode(verifyCode);
			entity.setTime(new Date());
			smsMobileService.save(entity);
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
			log.info("发送成功！");
		} catch (Exception e) {
			rm.setCode(ResultCodeValue.R_ERROR);
			rm.setMessage("发送失败");
			log.error("发送失败！");
		}
		return rm;
	}

	@ApiOperation(notes = "腾讯群发短信入口", value = "腾讯群发短信入口")
	@RequestMapping(value = "/tdSmsdMultiSender", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage SmsMultiSender(@RequestBody Map<String, Object> param) {
		ResponseMessage rm = this.getOperResultMap();
		try {
			String mobile = String.valueOf(param.get("mobile"));
			if (!mobile.contains(",")) {
				return this.getOperResultMap(ResultCodeValue.R_ERROR, "请用逗号隔开列表");
			}
			String[] mobiles = mobile.split(",");
			for (String index : mobiles) {
				if (!VerityUtil.isMobile(index)) {
					return this.getOperResultMap(ResultCodeValue.R_ERROR, "请输入正确的手机号码");
				}
			}
			String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
			String minute = Constant.TENCENT_SMS_FORGET_PASSWORD_MINUTE;
			String content = Constant.TENCENT_SMS_FORGET_PASSWORD_CONTENT.replace("verifyCode", verifyCode)
					.replace("minute", minute);
			rm = SMSUtil.sendQuerySMS(mobiles, content);
			log.info("发送成功！");
		} catch (Exception e) {
			rm.setCode(ResultCodeValue.R_ERROR);
			rm.setMessage("发送失败");
			log.error("发送失败！");
		}
		return rm;
	}
	
	
	/***
	 * 
	 * @Description:修改用户密码
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/updateUserInfomation", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "账号管理--修改手机", notes = "修改指定用户类型，并返回是否成功", position = 1)
	public ResponseMessage<Object> updateUserInfomation(HttpServletRequest request,@RequestBody Map<String, Object> param) {
		ResponseMessage<Object> rm = new ResponseMessage<Object>();
		try {
				String mobile = String.valueOf(param.get("mobile"));
				String oldMobile = String.valueOf(param.get("oldMobile"));
				String verifyCode = String.valueOf(param.get("verifyCode"));
				// 判断手机号码是否合法
				if (!VerityUtil.isMobile(mobile)) {
					rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "请输入正确的手机号码");
					return rm;
				}
				Map<String, Object> params =new HashMap<>();
				params.put("accountNo",mobile );
				User user1 = userService.getUserByParams(params );
				if (null!=user1) {
					rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "号码已经被使用");
					return rm;
				}
				//（已和产品确认）

//1.更换手机号
//----未在运营平台注册的手机号，也能通过小程序进行更换，身份不变，权限、功能和原来的一致
//2.更换后要重新验证新手机号是否与微信绑定的手机号一致，不一致提示无权限
//				String result=LesseeInfoUtil.getTenantInfoByTelAndProId(request, mobile);
//				JSONObject imis = JSONObject.parseObject(result);
//				String error=imis.getString("ErrorCode");
//				if ("0".equals(error)) {
//					User u1=LesseeInfoUtil.formartLesseeinfo2(result,mobile);
//					if (null==u1) {
//						rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "该号码在运营平台不存在");
//						return rm;
//					}
//				}
				SmsMobile smsMobile =smsMobileService.getByMobile(mobile);
				String randomCode = smsMobile.getVerifycode();
				if (!randomCode.equals(verifyCode)) {			
					rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "短信验证码错误");
					return rm;
					
				}
				params.remove("accountNo");
				params.put("openId", request.getHeader("openId"));
				User user = userService.getUserByParams(params);
				User u=new User();
				u.setAccountNo(mobile);
				u.setOldAccountNo(oldMobile);
				u.setId(user.getId());
				int count=userService.update(u);
				log.info("手机重置成功 " + count);
				rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
				//之后要删除redis中的缓存信息
				RedisUtils util= SpringUtils.getBean(RedisUtils.class);
				
				util.del(RedisKeyPrefix.USER_INFO,  request.getHeader("openId"));
				util.del(RedisKeyPrefix.USER_TOKEN,  request.getHeader("openId"));
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			log.error("用户手机号码修改出错！");
			e.printStackTrace();
		}
		return rm;

	}
}
